<?php namespace App\Http\Controllers\Api;

use App\Commission;
use App\CommissionDetail;
use App\DistributionConfig;
use App\DistributionList;
use App\DistributionTeam;
use App\DistributionWithdraw;
use App\Http\Controllers\Controller;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\Staff;
use App\UserInfo;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class DistributionController extends Controller
{
    /**
     * 小程序接口，获取用户中心中分销各类汇总信息接口，包含佣金明细列表和提现记录列表
     * @Author Jolly
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserDistributionInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        //获取每月开始和结束时间
        $month_first = date("Y-m-01", time());
        $month_end   = date("Y-m-t", time());

        $startTime = !is_null($request->get("start_time")) ? $request->get("start_time") : $month_first;
        $endTime   = !is_null($request->get("end_time")) ? $request->get("end_time") : $month_end;

        //可提现金额
        $userCommissions = Commission::whereUserId($user->id)->first();

        //分销商信息
        $thatDistribution = DistributionList::whereUserId($user->id)->first();

        $availableMoney = $userCommissions ? $userCommissions->available_money : 0; //可提现金额

        $distributionConfig = DistributionConfig::first();
        $minimalWithdrawLimit = $distributionConfig ? $distributionConfig->minimal_withdraw_limit : 0;

        //统计本月收入和订单情况及佣金明细
        $userCommissionsDetails = CommissionDetail::whereUserId($user->id)
            ->whereBetween("arrival_time",[$startTime,$endTime])
            ->whereStatus(1)
            ->get();

        $totalMoney               = CommissionDetail::whereUserId($user->id)->whereType(1)->whereStatus(1)->sum("amount"); //累计佣金
        $sectionTimeTotalMoney    = 0;
        $totalOrderNum            = CommissionDetail::whereUserId($user->id)->whereType(1)->whereStatus(1)->count();
        $sectionTimeTotalOrderNum = 0;

        if(count($userCommissionsDetails) > 0){
            foreach ($userCommissionsDetails as $userCommissionsDetail){
                $sectionTimeTotalMoney += $userCommissionsDetail->amount;
                $sectionTimeTotalOrderNum ++;

                //返成贡献者
                $fromUserBasicInfo = CommonManager::getUserBasicInfo($userCommissionsDetail->from_user_id);
                $userCommissionsDetail->from_user_info = $fromUserBasicInfo;
            }
        }

        //提现记录
        $withdraws = DistributionWithdraw::whereUserId($user->id)->orderBy("updated_at","desc")->get();
        if(count($withdraws) > 0){
            foreach ($withdraws as $withdraw){
                if($withdraw->review_status == 0 && $withdraw->transfer_status == 0){
                    $statusName = "待处理";
                }elseif ($withdraw->review_status == 1  && $withdraw->transfer_status == 0){
                    $statusName = "审核通过,待转账";
                }elseif ($withdraw->review_status == 1  && $withdraw->transfer_status == 1){
                    $statusName = "审核通过,转账完成";
                }elseif ($withdraw->review_status == 1  && $withdraw->transfer_status == 2){
                    $statusName = "审核通过,转账失败";
                }elseif ($withdraw->review_status == 1  && $withdraw->transfer_status == 3){
                    $statusName = "审核通过,转账中";
                }elseif ($withdraw->review_status == 2){
                    $statusName = "审核不通过";
                }

                $withdraw->status_name = $statusName;
            }
        }

        $result = [
            "available_money"              => $availableMoney,
            'minimal_withdraw_limit'       => $minimalWithdrawLimit,
            "total_money"                  => $totalMoney,
            "total_order_num"              => $totalOrderNum,
            "section_time_total_money"     => $sectionTimeTotalMoney,
            "section_time_total_order_num" => $sectionTimeTotalOrderNum,
            "commissions_list"             => $userCommissionsDetails,
            "withdraw_list"                => $withdraws
        ];

        return $this->successResponse('操作成功',$result);
    }

    /**
     * 小程序接口，用户申请提现接口
     * @author by Jolly
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws Exception
     */
    public function applyWithdrawal(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        $realname = $request->get("realname");
        $amount   = $request->get("amount");
        $phone    = $request->get("phone");

        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'success','message' => '请先登录！','data' => []]);

        $userInfo = $userInfo   = UserInfo::whereUserId($user->id)->first();

        if(is_null($realname) || trim($realname) == ''){
            return $this->parameterError("提现人姓名不能为空");
        }

        if(is_null($amount) || trim($amount) == ''){
            return $this->parameterError("提现金额不能为空");
        }

        if(is_null($phone) || trim($phone) == ''){
            return $this->parameterError("手机号不能为空");
        }

        $distributionConfigs = DistributionConfig::first();

        if($distributionConfigs && $distributionConfigs->minimal_withdraw_limit != ""){
            if($distributionConfigs->minimal_withdraw_limit > (float)$amount){
                return $this->parameterError("最低提现为".$distributionConfigs->minimal_withdraw_limit."元，提交失败");
            }
        }else{
            if($amount < 1){
                return $this->parameterError("提现金额需要大于1元，提交失败");
            }
        }

        //可提现金额
        $userCommissions = Commission::whereUserId($user->id)->first();
        if(!$userCommissions)
            return $this->dataError();

        if((float)$amount > $userCommissions->available_money){
            return $this->parameterError("不可大于您的可提现金额,提交失败！");
        }

        //开始佣金提现
        try{
            DB::beginTransaction();
            $newDistributionWithdraws = new DistributionWithdraw();
            $newDistributionWithdraws->user_id = $user->id;
            $newDistributionWithdraws->img_id  = $userInfo ? $userInfo->photo_id : 0;
            $newDistributionWithdraws->name    = $realname;
            $newDistributionWithdraws->phone   = $phone;
            $newDistributionWithdraws->withdraws_amount = $amount;
            $newDistributionWithdraws->withdraws_way = "wechat";
            $newDistributionWithdraws->withdrawal_num = "t".ToolsManager::makeBillNum();
            $newDistributionWithdraws->submit_time = date("Y-m-d H:i:s",time());
            $newDistributionWithdraws->save();

            $userCommissions->available_money = $userCommissions->available_money - $amount;
            $userCommissions->save();
            DB::commit();
        }catch (Exception $e){
            DB::rollBack();
            \Log::error($e->getTraceAsString());
            return response()->json(['level'=>'error','message'=>'提现错误，错误信息：'.$e->getMessage()]);
        }

        return $this->successResponse("提交成功,请耐心等待审核！");
    }

    /**
     * 小程序接口，用户获取分享海报接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\WechatException
     */
    public function getShareImg(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        $userInfo = UserInfo::whereUserId($user->id)->first();
        if(!$userInfo)
            return $this->dataError();

        if($userInfo && $userInfo->share_img_id == 0){
            $scene = "user_id=".$user->id;
            $path  = 'pages/index/index';

            //生成微信小程序的二维码图片
            $wxAppQrCodeContent = WechatLogin::getWxUnlimitQrcodeByToken($scene,$path);
            if($wxAppQrCodeContent) {
                //获取二维码图片
                $wxAppQrCodeImgINfo = Image::make($wxAppQrCodeContent)->resize(200, 200)->encode("image/jpeg");
                $qrcodeFile = FileManager::saveFileByFileContent($wxAppQrCodeImgINfo->encoded, 'qrcode_img.jpg', $wxAppQrCodeImgINfo->mime());
                $imageModel = new Images();
                $imageModel->files()->associate($qrcodeFile);
                $imageModel->img_type = $qrcodeFile->file_type;
                $imageModel->img_name = $qrcodeFile->file_name;
                $imageModel->save();

                $userInfo->qrcode_img_id = $imageModel->id;
                $userInfo->save();

                self::buildShareImg($userInfo);
            }
        }

        if($userInfo->qrcode_img_id == 0){
            self::buildShareImg($userInfo);
        }

        $userInfo->share_img_url = FileManager::getImgUrl($userInfo->share_img_id);

        return $this->successResponse("获取成功",$userInfo);
    }

    /**
     * 次级静态方法，生成分享海报
     * @param UserInfo $userInfo
     * @return UserInfo
     */
    public static function buildShareImg(UserInfo $userInfo){
//        $userInfo = UserInfo::whereUserId(166)->first();
        //背景图片
        $backgroundImgInfo = Image::make(url('images/share_bg.jpg'));

        $qrcodeImgInfo = Image::make(FileManager::getImgUrl($userInfo->qrcode_img_id))->resize(250, 250);
        $backgroundImgInfo->insert($qrcodeImgInfo,'top-left',250,524);
        $backgroundImgInfo->encode('jpg');

        //输出图片
        $qrcodeFile = FileManager::saveFileByFileContent($backgroundImgInfo->encoded, 'share_img.jpg', $backgroundImgInfo->mime());
        $imageModel = new Images();
        $imageModel->files()->associate($qrcodeFile);
        $imageModel->img_type = $qrcodeFile->file_type;
        $imageModel->img_name = $qrcodeFile->file_name;
        $imageModel->save();

        $userInfo->share_img_id = $imageModel->id;
        $userInfo->save();

        return $userInfo;

//        $response = response()->make($backgroundImgInfo->encode('jpg'));
//        $response->header('Content-Type', 'image/jpeg');
//        return $response;
    }

    public function getUserTeamsList(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        $distributionTeamsUserIds = DistributionTeam::whereUserId($user->id)->pluck("next_user_id")->toArray();
        $distributionLists = DistributionList::whereIn("user_id",$distributionTeamsUserIds)->orderBy("settling_time","desc")->get();
        if(count($distributionLists) > 0){
            foreach ($distributionLists as $distributionList){
                $distributionList->img_url = FileManager::getImgUrl($distributionList->img_id);
            }
        }

        return $this->successResponse("获取成功",$distributionLists);
    }
}
